# -*- coding: utf-8 -*-
"""
summary:
    博客 model
license:
    GNU General Public License v3 <http://www.gnu.org/licenses/gpl.html>
authors:
    Jason Lee <huacnlee@gmail.com>
"""

from django.db import models,connection
from django.contrib import admin
from django.utils.text import get_valid_filename
from django.core.urlresolvers import reverse
from settings import *
from apps.models import User
from utils import formatter,mailer
from utils.components import ExecuteState
from utils.dict import scores
import datetime


class License(models.Model):
    """
    summary:
        授权协议
    """
    TYPE_CHOICES = (
                    (1,'源代码'),
                    (2,'文章'),)
    name = models.CharField('协议名称',max_length=200)
    slug = models.CharField('slug',max_length=200)
    icon = models.CharField('图标',max_length=255,blank=True)
    type = models.IntegerField('类型',choices=TYPE_CHOICES,default=2)
    url = models.URLField('协议地址',blank=True)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'授权协议'
        verbose_name_plural = u'授权协议'

    def save(self):
        self.slug = get_valid_filename(self.slug.lower())
        super(License,self).save()


class Profile(models.Model):
    """
    summary:
        用户博客信息
    """
    user = models.OneToOneField(User)
    title = models.CharField('博客标题',max_length=255)
    slug = models.CharField('个性域名',max_length=255)
    sub_title = models.CharField('子标题',max_length=255,blank=True)
    face = models.ImageField('头像',upload_to='user/%s/face/' % slug,default='',blank=True)
    theme = models.CharField('博客主题',max_length=255,default=BLOG_DEFAULT_THEME)
    head_html = models.TextField('自定义HEADER',blank=True)
    page_size = models.IntegerField('每页篇数',default=20)
    allow_email_public = models.BooleanField('允许公开Email',default=False)
    allow_comment = models.BooleanField('允许评论',default=True)
    allow_trackback = models.BooleanField('允许引用',default=True)
    allow_auto_link = models.BooleanField('允许自动链接',default=True)
    default_license = models.ForeignKey(License,verbose_name='默认授权协议',null=True,blank=True)

    def __unicode__(self):
        return self.user.realname

    def get_absolute_url(self):
       return reverse('blog_home',args=[self.slug])

    def get_url(self):
        return '%s%s' % (APP_DOMAIN,self.get_absolute_url())

    class Meta:
        verbose_name = u'博客'
        verbose_name_plural = u'博客'

    def check_slug_exist(self):
        """
        summary:
            检查slug是否存在
        """
        state = ExecuteState()
        try:
            profile = Profile.objects.get(slug = self.slug)
            state.message = "“二级域名”已经被他人注冊，请更换一个。"
            state.success = False
        except (Profile.DoesNotExist):
            state.success = True
            profile = None

        return state

    def check(self):
        """
        summary:
            检测传入的内容是否符合要求
        """
        state = ExecuteState()
        state.success = False
        self.slug = get_valid_filename(self.slug.lower())

        state = self.check_slug_exist()
        if not state.success:
            return state
        state.success = True
        return state

    def save(self):
        self.slug = get_valid_filename(self.slug.lower())
        super(Profile,self).save()

class Category(models.Model):
    """
    summary:
        用户文章分类
    """
    profile = models.ForeignKey(Profile,verbose_name='用户')
    name = models.CharField('名称',max_length=20)
    slug = models.CharField('代码',max_length=20)
    sort = models.IntegerField('排序',default=0)
    post_count = models.IntegerField('文章数',default=0)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'文章分类'
        verbose_name_plural = u'文章分类'

    def save(self):
        self.slug = get_valid_filename(self.slug.lower())
        super(Category,self).save()


class Tag(models.Model):
    """
    summary:
        标签
    """
    name = models.CharField('名称',max_length=40)
    use_count = models.IntegerField('使用量',default=0)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'TAG'
        verbose_name_plural = u'TAG'


class ProfileTag(models.Model):
    """
    summary:
        用户Tag
    """
    profile = models.ForeignKey(Profile,verbose_name='用户')
    tag = models.ForeignKey(Tag,verbose_name='标签')
    use_count = models.IntegerField('使用数',default=0)

    def __unicode__(self):
        return '%s - %s' % (user.realname, tag.name)

    class Meta:
        verbose_name = u'用户TAG'
        verbose_name_plural = u'用户TAG'

class Post(models.Model):
    """
    summary:
        博客文章
    """
    STATUS_CHOICES = (
                      (0,'草稿'),
                      (1,'发布'),)
    profile = models.ForeignKey(Profile,verbose_name='用户')
    category = models.ForeignKey(Category,verbose_name='分类')
    title = models.CharField('标题',max_length=200)
    slug = models.CharField('slug',max_length=255,blank=True)
    summary = models.TextField('摘要',blank=True)
    body = models.TextField('正文')
    tags = models.ManyToManyField(ProfileTag,verbose_name='TAG',blank=True)
    meta_keywords = models.CharField('SEO关键词',max_length=255,default='',blank=True)
    meta_description = models.CharField('SEO摘要',max_length=255,default='',blank=True)
    status = models.IntegerField('状态',choices=STATUS_CHOICES,default=1)
    license = models.ForeignKey(License,verbose_name='授权协议',null=True)
    comment_count = models.IntegerField('评论数',default=0)
    view_count = models.IntegerField('访问量',default=0)
    digg_count = models.IntegerField('推荐次数',default=0)
    stay_on_top = models.BooleanField('置顶',default=False)
    allow_comment = models.BooleanField('允许评论',default=True)
    allow_trackback = models.BooleanField('允许引用',default=True)
    allow_auto_link = models.BooleanField('允许自动链接',default=True)
    allow_show_in_home = models.BooleanField('允许发布到首页',default=False)
    addtime = models.DateTimeField('添加时间',default=datetime.datetime.now())

    def __unicode__(self):
        return self.title

    def addtime_format(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    def get_absolute_url(self):
        return reverse('blog_post_view',args=[self.profile.slug,self.slug])

    def get_url(self):
        return '%s%s' % (APP_DOMAIN,self.get_absolute_url())

    class Meta:
        verbose_name = u'博客文章'
        verbose_name_plural = u'博客文章'



    def save(self):
        if self.slug.strip() == '':
            self.slug = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        else:
            self.slug = get_valid_filename(self.slug.lower())

        # 如果是新加的，处理积分的东西
        if not self.id:
            # 更新分类的文章个数
            self.category.post_count = self.category.post_count + 1
            self.category.save()

            # 更新积分
            self.profile.user.score = self.profile.user.score + scores.POST_ADD
            self.profile.user.save()

        super(Post,self).save()


    def delete(self):
        # 更新分类的文章个数
        self.category.post_count = self.category.post_count - 1
        self.category.save()
        # 更新积分
        self.profile.user.score = self.profile.user.score + scores.POST_DEL
        self.profile.user.save()

        super(Post,self).delete()

class Comment(models.Model):
    """
    summary:
        评论表
    """
    post = models.ForeignKey(Post,verbose_name='文章')
    profile = models.ForeignKey(Profile,verbose_name='评论者',null=True,blank=True)
    name = models.CharField('评论人',max_length=20,blank=True)
    url = models.URLField('博客',blank=True)
    email = models.EmailField('Email',blank=True)
    body = models.TextField('评论')
    ip = models.IntegerField('IP')
    follow = models.BooleanField('关注',default=False)
    addtime = models.DateTimeField('评论时间')

    class Meta:
        verbose_name = u'文章评论'
        verbose_name_plural = u'文章评论'

    def check(self):
        """
        summary:
            验证输入的内容是否符合要求，并返回 ExecuteState 状态
        returns:
            ExecuteState
        """
        state = ExecuteState()
        state.success = False

        if len(self.name) == 0:
            state.message = "还没有输入你的大名。"
            return state

        if len(self.body) < 4 or len(self.body) > 1000:
            state.message = '评论内容长度要求在4-1000字之内。'
            return state

        state.success = True
        return state

    def save(self):
        self.addtime = datetime.datetime.now()

        if self.url == 'http://':
            self.url = ''

        if not self.id:
            self.body = formatter.format_comment(self.body)

            # to save to sended email list
            sended_list = []

            # send to author
            mail_send = mailer.GotComment(self)
            mail_send.start()
            sended_list.append(self.post.profile.user.email)

            # send to follow user
            comments = Comment.objects.filter(follow = True,post__id = self.post.id)

            for c in comments:
                if c in sended_list:
                    mail_send1 = mailer.FollowComment(c)
                    sended_list.append(c.mail)
                    mail_send1.start()


        if self.profile:
            self.name = self.profile.user.realname
            self.url = self.profile.get_url()
            self.email = self.profile.user.email

            # user score
            if self.profile:
                self.profile.user.score = self.profile.user.score + scores.COMMENT_ADD
                self.profile.save()

        # update post comment_count
        self.post.comment_count = self.post.comment_count + 1
        self.post.save()

        # profile score
        self.post.profile.user.score = self.post.profile.user.score + scores.POST_COMMENT_ADD
        self.post.profile.user.save()


        super(Comment,self).save()



class PostDiggLog(models.Model):
    """
    summary:
        博客文章推荐记录
    """
    post = models.ForeignKey(Post)
    ip = models.IntegerField()
    addtime = models.DateTimeField()

    def save(self):
        self.addtime = datetime.datetime.now()
        super(PostDiggLog,self).save()
